package com.dormitory.httpHelper;

import com.dormitory.bean.UserBean;
import com.dormitory.staticVariable.StaticVariable;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by JHF on 2017/10/18.
 */

public class HttpLogin {
    public static int loginByGet(String name, String password, UserBean user) throws IOException, JSONException {
        URL url = new URL(StaticVariable.LOGIN_SERVLET);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setReadTimeout(5000);
        conn.setConnectTimeout(5000);
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("name", name);
        jsonObject.put("password", password);
        OutputStream out = conn.getOutputStream();
        out.write(jsonObject.toString().getBytes());
        out.flush();
        out.close();
        conn.connect();
        //Log.e("tag", conn.getResponseCode()+"");
        if(conn.getResponseCode() == 200) {
            InputStream is = conn.getInputStream();
            BufferedReader bf = new BufferedReader(new InputStreamReader(is));
            StringBuffer data0 = new StringBuffer();
            String buffer;
            while(((buffer) = bf.readLine())!=null) {
                data0.append(buffer);
            }
            JSONObject repJson = new JSONObject(data0.toString());
            String data = repJson.getString("result");
            if(data.equals("OK")) {
                user.setId(repJson.getInt("id"));
                user.setName(repJson.getString("name"));
                user.setDormitoryId(repJson.getInt("dormitoryId"));
                user.setPassword(repJson.getString("password"));
                user.setTelephone(repJson.getString("telephone"));
                return 0;
            }
            else {
                return 1;
            }
        }
        else
            return 2;   //网络错误
    }
}
